package com.ruoyi.system.service.impl;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.ruoyi.common.enums.PaOrderStatus;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.system.domain.PaOrderItem;
import com.ruoyi.system.domain.PaUserAddrOrder;
import com.ruoyi.system.domain.PaWxUser;
import com.ruoyi.system.domain.bo.PaOrderItemBo;
import com.ruoyi.system.domain.bo.PxBoxBo;
import com.ruoyi.system.domain.bo.SystemOrderRequestBo;
import com.ruoyi.system.domain.bo.SystemUpdateOrderBo;
import com.ruoyi.system.domain.vo.SystemOrderReponseVo;
import com.ruoyi.system.mapper.PaOrderItemMapper;
import com.ruoyi.system.mapper.PaUserAddrOrderMapper;
import com.ruoyi.system.mapper.PaWxUserMapper;
import com.ruoyi.system.service.IPxBoxService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.PaOrderMapper;
import com.ruoyi.system.domain.PaOrder;
import com.ruoyi.system.service.IPaOrderService;

/**
 * 代购订单（purchase agency）Service业务层处理
 *
 * @author ruoyi
 * @date 2024-07-03
 */
@Service
public class PaOrderServiceImpl implements IPaOrderService {
    @Autowired
    private PaOrderMapper paOrderMapper;

    @Autowired
    private PaOrderItemMapper paOrderItemMapper;

    @Autowired
    private PaUserAddrOrderMapper paUserAddrOrderMapper;

    @Autowired
    private PaWxUserMapper paWxUserMapper;

    @Autowired
    private IPxBoxService pxBoxService;

    /**
     * 查询代购订单（purchase agency）
     *
     * @param orderId 代购订单（purchase agency）主键
     * @return 代购订单（purchase agency）
     */
    @Override
    public SystemOrderReponseVo selectPaOrderByOrderId(Long orderId) {
        SystemOrderReponseVo paOrderReponseVo = new SystemOrderReponseVo();
        PaOrder paOrder = paOrderMapper.selectPaOrderByOrderId(orderId);
        BeanUtils.copyBeanProp(paOrderReponseVo, paOrder);
        //查询paOrderItem 商品信息
        PaOrderItem paOrderItem = new PaOrderItem();
        paOrderItem.setOrderId(paOrder.getOrderId());
        List<PaOrderItem> paOrderItems = paOrderItemMapper.selectPaOrderItemList(paOrderItem);
        List<PaOrderItemBo> paOrderItemBos = BeanUtil.copyToList(paOrderItems, PaOrderItemBo.class);
        paOrderReponseVo.setPaOrderItemBos(paOrderItemBos);
        //获取订单地址
        PaUserAddrOrder paUserAddrOrder = new PaUserAddrOrder();
        paUserAddrOrder.setOrderId(orderId);
        paOrderReponseVo.setPaUserAddrs(paUserAddrOrderMapper.selectPaUserAddrOrderList(paUserAddrOrder));

        //获取订单用户信息
        paOrderReponseVo.setPaWxUser(paWxUserMapper.selectPaWxUserByWxUserId(paOrder.getUserId()));
        //获取供应商用户信息
        paOrderReponseVo.setSupplierUser(paWxUserMapper.selectPaWxUserByWxUserId(paOrder.getSupplierId()));

        //根据orderId 查询拼箱信息
        paOrderReponseVo.setPxBox(pxBoxService.selectPxBoxByOrderId(orderId));
        return paOrderReponseVo;
    }

    /**
     * 查询代购订单（purchase agency）列表
     *
     * @param param 代购订单（purchase agency）
     * @return 代购订单（purchase agency）
     */
    @Override
    public List<SystemOrderReponseVo> selectPaOrderList(PaOrder param) {
        PaOrder paOrder = new PaOrder();
        BeanUtils.copyBeanProp(paOrder, param);
        List<PaOrder> paOrders = paOrderMapper.selectPaOrderList(paOrder);
        List<SystemOrderReponseVo> systemOrderReponseVos = BeanUtil.copyToList(paOrders, SystemOrderReponseVo.class);
        //查询paOrderItem 商品信息
        for (SystemOrderReponseVo reponseVo : systemOrderReponseVos) {
            PaOrderItem paOrderItem = new PaOrderItem();
            paOrderItem.setOrderId(reponseVo.getOrderId());
            List<PaOrderItem> paOrderItems = paOrderItemMapper.selectPaOrderItemList(paOrderItem);
            List<PaOrderItemBo> paOrderItemBos = BeanUtil.copyToList(paOrderItems, PaOrderItemBo.class);
            reponseVo.setPaOrderItemBos(paOrderItemBos);
            //获取供应商信息
            reponseVo.setSupplierUser(paWxUserMapper.selectPaWxUserByWxUserId(reponseVo.getSupplierId()));
            //获取订单用户信息
            reponseVo.setPaWxUser(paWxUserMapper.selectPaWxUserByWxUserId(Long.parseLong(reponseVo.getUserId())));
        }


        return systemOrderReponseVos;
    }

    /**
     * 新增代购订单（purchase agency）
     *
     * @param request 代购订单（purchase agency）
     * @return 结果
     */
    @Override
    public int insertPaOrder(SystemOrderRequestBo request) {
        //添加订单
        PaOrder paOrder = new PaOrder();
        BeanUtils.copyBeanProp(paOrder, request);
        paOrder.setCreateTime(DateUtils.getNowDate());
//        String orderNumber = String.valueOf(new Snowflake(1, 1).nextId());
//        paOrder.setOrderNumber(orderNumber);
        paOrder.setStatus(1);
        List<PaOrderItemBo> paOrderItemBos = request.getPaOrderItems();
        //如果商品为空抛出异常
        if (paOrderItemBos.isEmpty()) {
            throw new RuntimeException("商品不能为空");
        }
        String prodName = paOrderItemBos.stream()
                .map(PaOrderItemBo::getProdName)
                .collect(Collectors.joining(", "));
        paOrder.setProdName(prodName);
        paOrder.setCreateBy(String.valueOf(request.getUserId()));

        //判断用户对象信息是否为空，如果不为空根据手机号获取到用户id 不是保存
        if (request.getPaWxUser() != null) {
            PaWxUser paWxUser =  request.getPaWxUser();
            PaWxUser selectPaWxUserByPhone = paWxUserMapper.selectPaWxUserByPhone(paWxUser.getPhone());
            if (selectPaWxUserByPhone != null) {
            paOrder.setUserId(selectPaWxUserByPhone.getWxUserId());
            }
        }
        paOrderMapper.insertPaOrder(paOrder);
        Long orderId = paOrder.getOrderId();
        paOrderItemBos.forEach(x -> {
            x.setOrderId(Long.valueOf(orderId));
//            x.setOrderNumber(orderNumber);
            PaOrderItem paOrderItem = new PaOrderItem();
            BeanUtils.copyBeanProp(paOrderItem, x);
            paOrderItemMapper.insertPaOrderItem(paOrderItem);
        });
        // 获取paUserAddrs对象列表 并保存到数据库
        List<PaUserAddrOrder> paUserAddrs = request.getPaUserAddrs();
        paUserAddrs.forEach(paUserAddrOrder -> {
            paUserAddrOrder.setOrderId(Long.valueOf(orderId));
            paUserAddrOrder.setCreateTime(DateUtils.getNowDate());
            paUserAddrOrder.setUpdateTime(DateUtils.getNowDate());
            paUserAddrOrderMapper.insertPaUserAddrOrder(paUserAddrOrder);
        });

        return 0;
    }

    /**
     * 修改代购订单（purchase agency）
     *
     * @param paOrder 代购订单（purchase agency）
     * @return 结果
     */
    @Override
    public int updatePaOrder(SystemOrderRequestBo paOrder) {
        paOrder.setUpdateTime(DateUtils.getNowDate());
        PaOrder updatedPaOrder = new PaOrder();
        BeanUtils.copyBeanProp(updatedPaOrder, paOrder);
        List<PaOrderItemBo> paOrderItemBos = paOrder.getPaOrderItems();
        if (CollectionUtil.isNotEmpty(paOrderItemBos)) {
            String prodName = paOrderItemBos.stream()
                    .map(PaOrderItemBo::getProdName)
                    .collect(Collectors.joining(", "));
            updatedPaOrder.setProdName(prodName);
        }
        paOrderMapper.updatePaOrder(updatedPaOrder);
        //修改订单商品信息
        if (CollectionUtil.isNotEmpty(paOrderItemBos)) {
            for (PaOrderItemBo requestParam : paOrderItemBos) {
                PaOrderItem paOrderItem = new PaOrderItem();
                BeanUtils.copyBeanProp(paOrderItem, requestParam);
                paOrderItem.setUpdateTime(DateUtils.getNowDate());
                paOrderItem.setUpdateBy(paOrder.getUpdateBy());
                paOrderItemMapper.updatePaOrderItem(paOrderItem);
            }
        }
        //修改订单地址信息
        if (CollectionUtil.isNotEmpty(paOrder.getPaUserAddrs())) {
            for (PaUserAddrOrder requestParam : paOrder.getPaUserAddrs()) {
                PaUserAddrOrder paUserAddrOrder = new PaUserAddrOrder();
                BeanUtils.copyBeanProp(paUserAddrOrder, requestParam);
                paUserAddrOrder.setUpdateTime(DateUtils.getNowDate());
                paUserAddrOrder.setUpdateBy(paOrder.getUpdateBy());
                paUserAddrOrderMapper.updatePaUserAddrOrder(paUserAddrOrder);
            }
        }

        //修改供应商信息
    /*    if (Objects.nonNull(paOrder.getSupplierUser())) {
            paWxUserMapper.updatePaWxUser(paOrder.getSupplierUser());
        }*/
        //修改用户信息
      /*  if (Objects.nonNull(paOrder.getPaWxUser())) {
            paWxUserMapper.updatePaWxUser(paOrder.getPaWxUser());
        }*/
        //修改拼箱信息
        PxBoxBo pxBoxBo = paOrder.getPxBox();
        if (Objects.nonNull(pxBoxBo)) {
            pxBoxService.updatePxBox(pxBoxBo);
        }
        return 0;
    }

    /**
     * 批量删除代购订单（purchase agency）
     *
     * @param orderIds 需要删除的代购订单（purchase agency）主键
     * @return 结果
     */
    @Override
    public int deletePaOrderByOrderIds(Long[] orderIds) {
        return paOrderMapper.deletePaOrderByOrderIds(orderIds);
    }

    /**
     * 删除代购订单（purchase agency）信息
     *
     * @param orderId 代购订单（purchase agency）主键
     * @return 结果
     */
    @Override
    public int deletePaOrderByOrderId(Long orderId) {
        return paOrderMapper.deletePaOrderByOrderId(orderId);
    }

    @Override
    public int updatePaOrderPrice(SystemUpdateOrderBo systemUpdateOrder) {
        //根据orderId查询 paOrderItem
        PaOrderItem paOrderItem = new PaOrderItem();
        paOrderItem.setOrderId(systemUpdateOrder.getOrderId());
        List<PaOrderItem> paOrderItems = paOrderItemMapper.selectPaOrderItemList(paOrderItem);
        for (PaOrderItem paOrderItem1 : paOrderItems) {
            paOrderItem1.setActualUnintPrice(systemUpdateOrder.getActualUnintPrice());
            paOrderItem1.setUpdateTime(DateUtils.getNowDate());
            paOrderItem1.setUpdateBy(String.valueOf(systemUpdateOrder.getUpdateUserId()));
            paOrderItemMapper.updatePaOrderItem(paOrderItem1);
        }
        PaOrder paOrder = new PaOrder();
        paOrder.setOrderId(systemUpdateOrder.getOrderId());
        paOrder.setUpdateTime(DateUtils.getNowDate());
        //获取paOrderItemBos里面的 产品个数和产品单价 并相乘
        double prodCount = 0.0;
        for (PaOrderItem orderItem : paOrderItems) {
            double count = Double.parseDouble(orderItem.getProdCount());
            prodCount += count;
        }
        double actualUnintPrice = paOrderItems.stream()
                .filter(Objects::nonNull) // 过滤掉null值
                .map(PaOrderItem::getActualUnintPrice)
                .filter(Objects::nonNull)
                .mapToDouble(BigDecimal::doubleValue)
                .sum();
        // prodCount 和 actualTotal 相乘
        double actualTotal = prodCount * actualUnintPrice;
        paOrder.setActualTotal(new BigDecimal(String.valueOf(actualTotal)));
        paOrder.setStatus(PaOrderStatus.CONFIRMED.getCode());
        return paOrderMapper.updatePaOrder(paOrder);
    }
}
